<template>
	<form-container :title="'复制组织'" :width="550" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="目标组织：" name="targetId">
				<a-tree-select
					v-model:value="formData.targetId"
					style="width: 100%"
					:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
					placeholder="请选择目标组织"
					allow-clear
					tree-default-expand-all
					:tree-data="treeData"
					:field-names="{
						children: 'children',
						label: 'name',
						value: 'id'
					}"
					selectable="false"
					tree-line
				></a-tree-select>
			</a-form-item>
			<a-form-item label="包含子级：" name="containsChild">
				<a-radio-group v-model:value="formData.containsChild" :options="yesNoOptions"></a-radio-group>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" :loading="submitLoading" @click="onSubmit">保存</a-button>
		</template>
	</form-container>
</template>

<script setup name="orgCopy">
	import { required } from '@/utils/formRules'
	import orgApi from '@/api/sys/orgApi'
	import { getCurrentInstance } from 'vue'
	import tool from '@/utils/tool'

	// 定义emit事件
	const emit = defineEmits({ successful: null })
	const { proxy } = getCurrentInstance()
	// 默认是关闭状态
	let visible = ref(false)
	const formRef = ref()
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	// 定义机构元素
	const treeData = ref([])
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (selectedRowKey) => {
		visible.value = true
		formData.value = {
			ids: selectedRowKey,
			containsChild: 'true'
		}
		// 获取机构树并加入顶级
		orgApi.orgTree().then((res) => {
			treeData.value = [
				{
					id: 0,
					targetId: '-1',
					name: '顶级',
					children: res
				}
			]
		})
	}
	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		targetId: [required('请选择目标组织')],
		containsChild: [required('请选择包含子级')]
	}

	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			submitLoading.value = true
			orgApi
				.orgCopy(formData.value)
				.then(() => {
					visible.value = false
					emit('successful')
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	//是否字典
	let yesNoOptions = tool.dictList('YES_NO')
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
